package dongbai.soft.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import dongbai.soft.dao.CustomerDao;
import dongbai.soft.entity.CustomerEntity;
import dongbai.soft.service.CustomerService;
import dongbai.soft.utils.PageUtils;
import dongbai.soft.utils.Query;
import dongbai.soft.utils.R;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;


@Service("customerService")
public class CustomerServiceImpl extends ServiceImpl<CustomerDao, CustomerEntity> implements CustomerService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        Map<String, Object> filter = (Map<String, Object>) params.get("filter");
        IPage<CustomerEntity> page = this.page(
                new Query<CustomerEntity>().getPage(params),
                new QueryWrapper<CustomerEntity>().like("name", filter.get("name"))
                        .like("phone", filter.get("phone"))
                        .eq("status", 1)
        );

        return new PageUtils(page);
    }

    public boolean isRepeate(String name, String phone, String cid) {
        List<CustomerEntity> userEntities = this.list(new QueryWrapper<CustomerEntity>().eq("name", name)
                .eq("phone", phone).ne("CID", cid));
        return userEntities.size() == 0;
    }

    @Override
    public R addCustomer(CustomerEntity customer) {
        if (isRepeate(customer.getName(), customer.getPhone(), customer.getCid())) {
            this.save(customer);
            return R.ok("添加成功");
        }
        return R.error("已存在该客户");
    }

    @Override
    public R deleteCustomer(String cid) {
        this.update(new UpdateWrapper<CustomerEntity>().eq("CID", cid).set("status", 0));
        return R.ok("删除成功");
    }

    @Override
    public R editCustomer(CustomerEntity customer) {
        if (isRepeate(customer.getName(), customer.getPhone(), customer.getCid())) {
            System.out.println(customer);
            this.update(new UpdateWrapper<CustomerEntity>()
                    .eq("CID", customer.getCid())
                    .set("name", customer.getName())
                    .set("phone", customer.getPhone())
                    .set("addresses", customer.getAddresses())
            );
            return R.ok("修改成功");
        }
        return R.error("已存在该客户");
    }


}